﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml.Serialization;

namespace Oridea.Data.Fetching.Example {
	public class CustomerRepository {
		// For example purposes, already loaded data is used. However, the Fetching library
		// will work with any LINQ supporting ORM framework.
		private static readonly IQueryable<Customer> DataSource;

		static CustomerRepository() {
			List<Customer> customers = new List<Customer>();

			using (StreamReader streamReader = new StreamReader(
				Assembly.GetExecutingAssembly().GetManifestResourceStream("Oridea.Data.Fetching.Example.Customers.xml"))) {
				customers = (List<Customer>)new XmlSerializer(typeof(List<Customer>)).Deserialize(streamReader);
			}

			// This is for example purposes only, in real line-of-business application,
			// DataSource is usually provided by an ORM framework.
			DataSource = customers.AsQueryable();
		}

		public IOrderableFetcher<Customer> GetByName(string namePattern) {
			return new CollectionFetcher<Customer>(
				from customer in DataSource
				where customer.FirstName.Contains(namePattern) || customer.LastName.Contains(namePattern)
				select customer);
		}

		public IFetcher<Dictionary<int, string>> GetNameByIdDictionary() {
			return new DictionaryFetcher<Customer, int, string>(
				DataSource,
				customer => customer.Id,
				customer => customer.FirstName + " " + customer.LastName);
		}

		public static OrderingSequence<Customer> SorterByNameAndId {
			get {
				return new OrderingSequence<Customer> {
					customer => customer.FirstName,
					customer => customer.LastName,
					customer => customer.Id
				};
			}
		}
	}
}
